import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../data/services/data_management_service.dart';

/// 数据库表结构查看组件
/// 显示数据库表的结构信息
class TableSchemaWidget extends ConsumerStatefulWidget {
  final Map<String, dynamic> connectionConfig;
  final String tableName;

  const TableSchemaWidget({
    super.key,
    required this.connectionConfig,
    required this.tableName,
  });

  @override
  ConsumerState<TableSchemaWidget> createState() => _TableSchemaWidgetState();
}

class _TableSchemaWidgetState extends ConsumerState<TableSchemaWidget> {
  List<Map<String, dynamic>> _schema = [];
  bool _isLoading = false;
  String? _error;

  @override
  void initState() {
    super.initState();
    _loadTableSchema();
  }

  /// 加载表结构信息
  Future<void> _loadTableSchema() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      final dataManagementService = DataManagementService();
      _schema = await dataManagementService.getTableSchema(
        widget.connectionConfig,
        widget.tableName,
      );

      setState(() {
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _error = '加载表结构失败: ${e.toString()}';
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.all(16),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                const SelectableText(
                  '表结构信息',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const Spacer(),
                IconButton(
                  icon: const Icon(Icons.refresh),
                  onPressed: _loadTableSchema,
                  tooltip: '刷新',
                ),
              ],
            ),
            const SizedBox(height: 16),
            if (_isLoading)
              const Center(
                child: Column(
                  children: [
                    CircularProgressIndicator(),
                    SizedBox(height: 16),
                    SelectableText('正在加载表结构...'),
                  ],
                ),
              )
            else if (_error != null)
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.red.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.red.withValues(alpha: 0.3)),
                ),
                child: Column(
                  children: [
                    const Icon(Icons.error, color: Colors.red),
                    const SizedBox(height: 8),
                    SelectableText(
                      _error!,
                      style: const TextStyle(color: Colors.red),
                      textAlign: TextAlign.center,
                    ),
                    const SizedBox(height: 8),
                    ElevatedButton(
                      onPressed: _loadTableSchema,
                      child: const SelectableText('重试'),
                    ),
                  ],
                ),
              )
            else if (_schema.isEmpty)
              Center(
                child: SelectableText(
                  '表 ${widget.tableName} 不存在或无数据',
                  style: const TextStyle(color: Colors.grey),
                  textAlign: TextAlign.center,
                ),
              )
            else
              _buildSchemaTable(),
          ],
        ),
      ),
    );
  }

  Widget _buildSchemaTable() {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: DataTable(
        columns: const [
          DataColumn(
              label: SelectableText('列名',
                  style: TextStyle(fontWeight: FontWeight.bold))),
          DataColumn(
              label: SelectableText('数据类型',
                  style: TextStyle(fontWeight: FontWeight.bold))),
          DataColumn(
              label: SelectableText('可空',
                  style: TextStyle(fontWeight: FontWeight.bold))),
          DataColumn(
              label: SelectableText('主键',
                  style: TextStyle(fontWeight: FontWeight.bold))),
        ],
        rows: _schema.map((column) {
          return DataRow(
            cells: [
              DataCell(SelectableText(column['column_name'] as String)),
              DataCell(SelectableText(column['data_type'] as String)),
              DataCell(
                Icon(
                  column['is_nullable'] as bool ? Icons.check : Icons.close,
                  color:
                      column['is_nullable'] as bool ? Colors.green : Colors.red,
                ),
              ),
              DataCell(
                Icon(
                  column['is_primary_key'] as bool ? Icons.check : Icons.close,
                  color: column['is_primary_key'] as bool
                      ? Colors.green
                      : Colors.red,
                ),
              ),
            ],
          );
        }).toList(),
      ),
    );
  }
}
